<template>
  <fieldset>
    <legend>按钮鉴权</legend>
    <div id="app">
      <!-- 登录之后的结构，因为需要隐藏，且v-if要写在v-else前面，
                 所以登录之后的结构写在前面 -->
      <div class="content" v-if="isLogin">
        <ul>
          <li v-for="(item, index) of arr" :key="index">
            <b>{{ item }}</b>
            <button v-has:[buttons]="'add'">增加</button>
            <button v-has:[buttons]="'edit'">编辑</button>
            <button v-has:[buttons]="'delete'">删除</button>
            <button v-has:[buttons]="'read'">查看</button>
          </li>
        </ul>
      </div>

      <!-- 登录的结构 -->
      <div class="login-container" v-else>
        <h1>请登录</h1>
        <span>admin</span><br />
        用户姓名:<input type="text" v-model="username" /><br />
        输入密码:<input
          type="password"
          v-model="password"
          @keydown.enter="login"
        />
        <button @click="login">点击登录</button>
      </div>
    </div>
  </fieldset>
</template>

<script>
export default {
  data() {
    return {
      username: "", //用户名
      password: "", //密码
      isLogin: false, //定义是否登入
      arr: ["吃饭", "睡觉", "删库", "跑路"],
      buttons: [], //按钮权限
    };
  },
  directives: {
    has: {
      //自定义指令,控制按钮
      inserted(el, binding) {
        console.log(el);
        console.log(binding);
        //判断用户的权限数组(buttons) 是否包含 binding.value(需要具备的权限)
        //包含就展示 不包含就移除
        //this获取不到当前实例
        //数组的includes方法
        let hasPermission = binding.arg.includes(binding.value);
        if (!hasPermission) {
          el.parentNode.removeChild(el); //没有权限就把当前按钮移除掉
        }
      },
    },
  },
  methods: {
    async login() {
      //获取输入框的内容，发起请求，数据对象传给后台
      let body = {
        username: this.username,
        password: this.password,
      };
      //用fetch发起请求
      //登录请求
      let result = await fetch("http://chst.vip/users/login", {
        method: "post",
        body: JSON.stringify(body),
        headers: {
          "content-type": "application/json",
        },
      }).then((body) => body.json());

      console.log(result);
      //将数据进行解构
      let {
        state,
        permission: { buttons },
      } = result;
      if (state) {
        //登录成功,将登录状态变更为true
        this.isLogin = true;
        //buttons是后台返回的用户的按钮的求安县
        this.buttons = buttons;
      }
    },
  },
};
</script>
